package com.icinfo.cloud.provider.peripheralinterface.electricinvoice.service.impl;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.dto.FileInfoSaveDto;
import com.icinfo.cloud.provider.common.enums.AttachmentRequestContentTypeEnum;
import com.icinfo.cloud.provider.common.enums.FileTransferFormEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.oss.service.IOssOperateService;
import com.icinfo.cloud.provider.common.utils.AesUtil;
import com.icinfo.cloud.provider.common.utils.HttpUtils;
import com.icinfo.cloud.provider.common.utils.RSAEncryptUtil;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.dto.ElectricInvoiceRequest;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.service.IElectricInvoiceInterface;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.vo.ElectricInvoicePdfVo;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentResultRecordMapper;
import com.icinfo.framework.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：电子发票接口实现类
 *
 * @author xiangyuyu
 * @date 2022/6/17 11:22
 */
@Service
@Slf4j
public class ElectricInvoiceInterfaceImpl implements IElectricInvoiceInterface {
    @Value("${electricInvoice.privateKey}")
    private String privateKey;
    @Value("${electricInvoice.publicKey}")
    private String publicKey;
    @Value("${electricInvoice.channelNo}")
    private String channelNo;
    @Value("${electricInvoice.aesKey}")
    private String aesKey;
    @Value("${electricInvoice.url}")
    private String url;
    @Value("${paymentCq.getElcInvoicePicUrl}")
    private String getElcInvoicePicUrl;
    @Resource
    private IOssOperateService ossOperateService;
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private CasePaymentResultRecordMapper casePaymentResultRecordMapper;

    /**
     * 【V1.3.0】描述：获取电子发票信息
     *
     * @param request {@link ElectricInvoiceRequest}
     * @return List<String> 电子发票列表（1个或多个）
     * @author xiangyuyu
     * @date 2022-04-08 16:58
     */
    @Override
    public List<String> getElectricInvoice(ElectricInvoiceRequest request) {
        /*if (!ObjectUtil.isEmpty(request.getChannelNo())) {
            channelNo = request.getChannelNo();
        }
        Map<String, Object> map = new HashMap<>(8);
        map.put("channelNo", channelNo);
        map.put("certificateNo", request.getCertificateNo());
        map.put("checkCode", request.getCheckCode());
        map.put("enterCode", request.getEnterCode());
        StringBuilder sb = new StringBuilder();
        map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&")
        );
        String paramStr = sb.toString().substring(0, sb.length() - 1);
        String sign = RSAEncryptUtil.sign(privateKey, paramStr);
        HashMap<Object, Object> map1 = new HashMap<>(8);
        String aesStr = JSON.toJSONString(map);
        String encryptStr = AesUtil.aesEncrypt(aesStr, aesKey);
        map1.put("bizContent", encryptStr);
        map1.put("authorization", "33000003");
        map1.put("sign", sign);
        map1.put("timestamp", System.currentTimeMillis());*/
        HashMap<Object, Object> map1 = new HashMap<>(8);
        map1.put("electricInvoiceAddress",request.getElectricInvoiceAddress());
        JSON json = (JSON) JSON.toJSON(map1);
        String httpResult = HttpUtils.doPostJson(getElcInvoicePicUrl, json.toJSONString());
        log.info("httpResult:{}",httpResult);
        //{"timestamp":"2022-06-17T03:07:16.380+0000","status":500,"error":"Internal Server Error","message":"No message available","path":"/elnvoices/api/downloadPDF"}
        ElectricInvoicePdfVo picResponse = JSON.parseObject(httpResult, ElectricInvoicePdfVo.class);
        if (picResponse.getNum() > 0) {
            List<String> pdfStrList = picResponse.getPdfStrList();
            List<String> pdfOssAddressList = new ArrayList<>();
            for (int i = 0; i < pdfStrList.size(); i++) {
                byte[] info = Base64Decoder.decode(pdfStrList.get(i).getBytes(StandardCharsets.UTF_8));
                //上传oss
                FileInfoSaveDto fileInfo = new FileInfoSaveDto();
                fileInfo.setFileBytes(info);
                fileInfo.setFileTransferForm(FileTransferFormEnum.FILE_TRANSFER_FORM_3.getCode());
                fileInfo.setFileType(AttachmentRequestContentTypeEnum.png.getCode());
                Result result = ossOperateService.uploadFile(fileInfo);
                if (!ObjectUtils.isEmpty(result)) {
                    Object data = result.getData();
                    if (ObjectUtils.isEmpty(data)) {
                        throw new BusinessException("getElectricInvoice upload file to oss fail-address is null");
                    } else {
                        pdfOssAddressList.add(data.toString());
                    }
                } else {
                    throw new BusinessException("getElectricInvoice upload file to oss fail-response is null");
                }
            }
            if (Constant.STRING_2.equals(request.getResponseFileFormatType())) {
                return pdfOssAddressList;
            } else {
                return pdfStrList;
            }
        }
        return null;
    }

}
